package com.qingzhuge.manager.security.handler;

import cn.hutool.http.HttpStatus;
import com.google.gson.Gson;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.dto.response.ResponseBodyDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zeroxiao
 * @date 2019/9/12 12:03
 */
@Slf4j
public class DefinedAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (log.isDebugEnabled()) {
            String method = request.getMethod();
            String uri = request.getRequestURI();
            log.debug("权限不足:[{}]-[{}] [{}]",method,uri, accessDeniedException.getMessage());
        }
        response.setCharacterEncoding("UTF8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResponseBodyDto<String> result = new ResponseBodyDto<>();
        result.setCode(HttpCode.UNAUTHORIZED.value());
        result.setMessage(HttpCode.UNAUTHORIZED.message());
        response.setStatus(HttpStatus.HTTP_OK);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new Gson().toJson(result));
    }
}
